import openpyxl
import os

# 设置文件路径
base_dir = "e:/Projects/program-py/LEARN-数据分析/CASE-Excel_merge"
employee_info_file = f"{base_dir}/员工基本信息表.xlsx"
performance_file = f"{base_dir}/员工绩效表.xlsx"

def read_excel_preview(file_path):
    """读取Excel文件的前5行数据"""
    try:
        # 加载工作簿
        workbook = openpyxl.load_workbook(file_path, data_only=True)
        # 获取第一个工作表
        sheet = workbook.active
        
        # 读取前5行数据
        data = []
        for row in sheet.iter_rows(min_row=1, max_row=5, values_only=True):
            data.append(row)
        
        workbook.close()
        return data
    except Exception as e:
        print(f"读取文件 {file_path} 时出错: {e}")
        return None

def print_table(data, title):
    """格式化打印表格数据"""
    if not data:
        return
    
    print(f"\n{title}")
    print("-" * 50)
    
    # 找出每列的最大宽度
    max_widths = []
    for col in range(len(data[0])):
        max_width = max(len(str(row[col])) if row[col] is not None else 0 for row in data)
        max_widths.append(max(max_width, 10))  # 最小宽度为10
    
    # 打印表头和数据
    for i, row in enumerate(data):
        row_str = ""
        for j, cell in enumerate(row):
            cell_value = str(cell) if cell is not None else ""
            row_str += f"{cell_value:<{max_widths[j]}}  "
        print(row_str)
        
        if i == 0:  # 在表头后添加分隔线
            print("-" * 50)

def main():
    print("=" * 60)
    print("读取Excel文件前5行数据")
    print("=" * 60)
    
    # 读取员工基本信息表
    employee_info = read_excel_preview(employee_info_file)
    if employee_info is not None:
        print_table(employee_info, "1. 员工基本信息表.xlsx - 前5行:")
        print(f"数据行数: {len(employee_info)}")
    else:
        print("无法读取员工基本信息表")
    
    # 读取员工绩效表
    performance = read_excel_preview(performance_file)
    if performance is not None:
        print_table(performance, "\n2. 员工绩效表.xlsx - 前5行:")
        print(f"数据行数: {len(performance)}")
    else:
        print("无法读取员工绩效表")
    
    print("\n" + "=" * 60)
    print("读取完成!")

if __name__ == "__main__":
    main()